// AI智能推荐引擎
// 基于多维度因素的个性化菜品推荐系统

class AIRecommendationEngine {
    constructor() {
        this.weatherAPI = 'https://api.openweathermap.org/data/2.5/weather';
        this.weatherAPIKey = 'your_api_key_here'; // 需要申请API密钥
        this.currentWeather = null;
        this.userPreferences = this.loadUserPreferences();
        this.recommendationHistory = this.loadRecommendationHistory();
    }

    // 获取当前时间信息
    getCurrentTimeInfo() {
        const now = new Date();
        const hour = now.getHours();
        const dayOfWeek = now.getDay();
        const month = now.getMonth() + 1;
        
        return {
            hour: hour,
            dayOfWeek: dayOfWeek,
            month: month,
            season: this.getSeason(month),
            timeOfDay: this.getTimeOfDay(hour),
            isWeekend: dayOfWeek === 0 || dayOfWeek === 6
        };
    }

    // 获取季节
    getSeason(month) {
        if (month >= 3 && month <= 5) return 'spring';
        if (month >= 6 && month <= 8) return 'summer';
        if (month >= 9 && month <= 11) return 'autumn';
        return 'winter';
    }

    // 获取时段
    getTimeOfDay(hour) {
        if (hour >= 6 && hour < 10) return 'morning';
        if (hour >= 10 && hour < 14) return 'lunch';
        if (hour >= 14 && hour < 17) return 'afternoon';
        if (hour >= 17 && hour < 21) return 'dinner';
        if (hour >= 21 || hour < 6) return 'night';
        return 'unknown';
    }

    // 获取天气信息（模拟）
    async getWeatherInfo() {
        // 模拟天气数据，实际应用中需要调用天气API
        const weatherConditions = [
            { condition: 'sunny', temperature: 25, humidity: 60 },
            { condition: 'rainy', temperature: 18, humidity: 85 },
            { condition: 'cloudy', temperature: 22, humidity: 70 },
            { condition: 'snowy', temperature: -5, humidity: 90 },
            { condition: 'hot', temperature: 35, humidity: 50 }
        ];
        
        // 随机选择天气条件
        const randomWeather = weatherConditions[Math.floor(Math.random() * weatherConditions.length)];
        
        return {
            condition: randomWeather.condition,
            temperature: randomWeather.temperature,
            humidity: randomWeather.humidity,
            description: this.getWeatherDescription(randomWeather.condition)
        };
    }

    // 获取天气描述
    getWeatherDescription(condition) {
        const descriptions = {
            'sunny': '阳光明媚，适合清爽食物',
            'rainy': '雨天湿润，推荐热汤暖身',
            'cloudy': '多云天气，适合各种口味',
            'snowy': '寒冷天气，推荐热食暖胃',
            'hot': '炎热天气，推荐清凉解暑'
        };
        return descriptions[condition] || '天气宜人，推荐美食';
    }

    // 分析用户历史偏好
    analyzeUserPreferences(userId) {
        const orders = this.getUserOrders(userId);
        const preferences = {
            favoriteCategories: {},
            favoriteMerchants: {},
            favoriteDishes: {},
            timePreferences: {},
            priceRange: { min: 0, max: 0 },
            spicyLevel: 0,
            healthyPreference: 0
        };

        if (orders.length === 0) {
            return this.getDefaultPreferences();
        }

        // 分析订单数据
        orders.forEach(order => {
            order.dishes.forEach(dish => {
                // 统计菜品类别偏好
                if (!preferences.favoriteCategories[dish.category]) {
                    preferences.favoriteCategories[dish.category] = 0;
                }
                preferences.favoriteCategories[dish.category]++;

                // 统计商家偏好
                if (!preferences.favoriteMerchants[order.merchantId]) {
                    preferences.favoriteMerchants[order.merchantId] = 0;
                }
                preferences.favoriteMerchants[order.merchantId]++;

                // 统计菜品偏好
                if (!preferences.favoriteDishes[dish.id]) {
                    preferences.favoriteDishes[dish.id] = 0;
                }
                preferences.favoriteDishes[dish.id]++;

                // 分析价格偏好
                const price = dish.price;
                if (preferences.priceRange.min === 0 || price < preferences.priceRange.min) {
                    preferences.priceRange.min = price;
                }
                if (price > preferences.priceRange.max) {
                    preferences.priceRange.max = price;
                }
            });

            // 分析时间偏好
            const orderHour = new Date(order.orderTime).getHours();
            const timeSlot = this.getTimeOfDay(orderHour);
            if (!preferences.timePreferences[timeSlot]) {
                preferences.timePreferences[timeSlot] = 0;
            }
            preferences.timePreferences[timeSlot]++;
        });

        return preferences;
    }

    // 获取默认偏好
    getDefaultPreferences() {
        return {
            favoriteCategories: {},
            favoriteMerchants: {},
            favoriteDishes: {},
            timePreferences: {},
            priceRange: { min: 10, max: 50 },
            spicyLevel: 2,
            healthyPreference: 3
        };
    }

    // 获取用户订单
    getUserOrders(userId) {
        const orders = JSON.parse(localStorage.getItem('orders') || '[]');
        return orders.filter(order => order.userId === userId);
    }

    // 计算菜品推荐分数
    calculateDishScore(dish, userPreferences, timeInfo, weatherInfo) {
        let score = 0;
        const factors = [];

        // 1. 基础分数（菜品评分和销量）
        score += dish.rating * 10;
        score += Math.min(dish.sales / 10, 50); // 销量影响，最高50分
        factors.push(`基础分数: ${Math.round(score)}`);

        // 2. 时间匹配度
        const timeScore = this.getTimeScore(dish, timeInfo);
        score += timeScore;
        factors.push(`时间匹配: +${Math.round(timeScore)}`);

        // 3. 天气匹配度
        const weatherScore = this.getWeatherScore(dish, weatherInfo);
        score += weatherScore;
        factors.push(`天气匹配: +${Math.round(weatherScore)}`);

        // 4. 用户偏好匹配度
        const preferenceScore = this.getPreferenceScore(dish, userPreferences);
        score += preferenceScore;
        factors.push(`偏好匹配: +${Math.round(preferenceScore)}`);

        // 5. 季节匹配度
        const seasonScore = this.getSeasonScore(dish, timeInfo.season);
        score += seasonScore;
        factors.push(`季节匹配: +${Math.round(seasonScore)}`);

        // 6. 价格合理性
        const priceScore = this.getPriceScore(dish, userPreferences.priceRange);
        score += priceScore;
        factors.push(`价格合理: +${Math.round(priceScore)}`);

        // 7. 库存状态
        if (dish.stock > 0) {
            score += 10;
            factors.push(`有库存: +10`);
        } else {
            score -= 50;
            factors.push(`无库存: -50`);
        }

        return {
            score: Math.max(0, score),
            factors: factors
        };
    }

    // 时间匹配分数
    getTimeScore(dish, timeInfo) {
        const timePreferences = {
            'morning': ['粥类', '包子', '豆浆', '面条', '早餐'],
            'lunch': ['米饭', '面条', '快餐', '套餐', '主食'],
            'afternoon': ['茶点', '甜品', '小食', '饮品'],
            'dinner': ['正餐', '火锅', '烧烤', '大菜'],
            'night': ['夜宵', '烧烤', '小吃', '饮品']
        };

        const preferredCategories = timePreferences[timeInfo.timeOfDay] || [];
        const categoryMatch = preferredCategories.some(cat => 
            dish.category.includes(cat) || dish.name.includes(cat)
        );

        if (categoryMatch) {
            return 20;
        }

        // 特殊时段推荐
        if (timeInfo.timeOfDay === 'morning' && dish.tags.includes('早餐')) {
            return 25;
        }
        if (timeInfo.timeOfDay === 'night' && dish.tags.includes('夜宵')) {
            return 25;
        }

        return 0;
    }

    // 天气匹配分数
    getWeatherScore(dish, weatherInfo) {
        const weatherPreferences = {
            'sunny': ['清爽', '凉菜', '沙拉', '冷饮', '水果'],
            'rainy': ['热汤', '火锅', '热饮', '暖身'],
            'cloudy': ['家常', '经典', '传统'],
            'snowy': ['热食', '火锅', '热汤', '暖胃'],
            'hot': ['清凉', '冷饮', '沙拉', '水果', '解暑']
        };

        const preferredKeywords = weatherPreferences[weatherInfo.condition] || [];
        const description = dish.description.toLowerCase();
        const name = dish.name.toLowerCase();

        let matchCount = 0;
        preferredKeywords.forEach(keyword => {
            if (description.includes(keyword) || name.includes(keyword)) {
                matchCount++;
            }
        });

        return matchCount * 15;
    }

    // 偏好匹配分数
    getPreferenceScore(dish, userPreferences) {
        let score = 0;

        // 类别偏好
        if (userPreferences.favoriteCategories[dish.category]) {
            score += userPreferences.favoriteCategories[dish.category] * 5;
        }

        // 商家偏好
        if (userPreferences.favoriteMerchants[dish.merchantId]) {
            score += userPreferences.favoriteMerchants[dish.merchantId] * 3;
        }

        // 菜品偏好
        if (userPreferences.favoriteDishes[dish.id]) {
            score += userPreferences.favoriteDishes[dish.id] * 10;
        }

        return Math.min(score, 50); // 最高50分
    }

    // 季节匹配分数
    getSeasonScore(dish, season) {
        const seasonPreferences = {
            'spring': ['清淡', '新鲜', '蔬菜', '春菜'],
            'summer': ['清凉', '解暑', '冷饮', '沙拉'],
            'autumn': ['温补', '润燥', '秋菜', '养生'],
            'winter': ['温补', '暖身', '热食', '进补']
        };

        const preferredKeywords = seasonPreferences[season] || [];
        const description = dish.description.toLowerCase();
        const name = dish.name.toLowerCase();

        let matchCount = 0;
        preferredKeywords.forEach(keyword => {
            if (description.includes(keyword) || name.includes(keyword)) {
                matchCount++;
            }
        });

        return matchCount * 10;
    }

    // 价格合理性分数
    getPriceScore(dish, priceRange) {
        const price = dish.price;
        const { min, max } = priceRange;

        if (price >= min && price <= max) {
            return 20;
        } else if (price < min) {
            return 15; // 价格偏低，可能质量一般
        } else {
            return Math.max(0, 20 - (price - max) * 2); // 价格过高扣分
        }
    }

    // 生成个性化推荐
    async generateRecommendations(userId, limit = 10) {
        try {
            // 获取基础数据
            const dishes = JSON.parse(localStorage.getItem('dishes') || '[]');
            const timeInfo = this.getCurrentTimeInfo();
            const weatherInfo = await this.getWeatherInfo();
            const userPreferences = this.analyzeUserPreferences(userId);

            // 计算每个菜品的推荐分数
            const scoredDishes = dishes.map(dish => {
                const scoreResult = this.calculateDishScore(dish, userPreferences, timeInfo, weatherInfo);
                return {
                    ...dish,
                    recommendationScore: scoreResult.score,
                    scoreFactors: scoreResult.factors,
                    recommendationReason: this.generateRecommendationReason(dish, scoreResult.factors, timeInfo, weatherInfo)
                };
            });

            // 按分数排序
            let recommendations = scoredDishes
                .sort((a, b) => b.recommendationScore - a.recommendationScore);

            // 应用用户行为学习优化
            recommendations = this.optimizeRecommendations(userId, recommendations);

            // 返回前N个推荐
            recommendations = recommendations.slice(0, limit);

            // 记录推荐历史
            this.recordRecommendationHistory(userId, recommendations);

            return {
                recommendations: recommendations,
                context: {
                    timeInfo: timeInfo,
                    weatherInfo: weatherInfo,
                    userPreferences: userPreferences
                }
            };
        } catch (error) {
            console.error('生成推荐失败:', error);
            return { recommendations: [], context: null };
        }
    }

    // 生成推荐理由
    generateRecommendationReason(dish, factors, timeInfo, weatherInfo) {
        const reasons = [];

        // 时间相关理由
        if (timeInfo.timeOfDay === 'morning') {
            reasons.push('适合早餐时间');
        } else if (timeInfo.timeOfDay === 'lunch') {
            reasons.push('午餐时间推荐');
        } else if (timeInfo.timeOfDay === 'dinner') {
            reasons.push('晚餐时间推荐');
        }

        // 天气相关理由
        if (weatherInfo.condition === 'rainy') {
            reasons.push('雨天暖身推荐');
        } else if (weatherInfo.condition === 'hot') {
            reasons.push('炎热天气解暑推荐');
        } else if (weatherInfo.condition === 'sunny') {
            reasons.push('阳光明媚，清爽推荐');
        }

        // 菜品特色理由
        if (dish.tags.includes('热卖')) {
            reasons.push('热门菜品');
        }
        if (dish.tags.includes('折扣')) {
            reasons.push('限时优惠');
        }
        if (dish.rating >= 4.5) {
            reasons.push('高评分菜品');
        }

        return reasons.length > 0 ? reasons.join('，') : '为您精心推荐';
    }

    // 记录推荐历史
    recordRecommendationHistory(userId, recommendations) {
        const history = this.recommendationHistory[userId] || [];
        const record = {
            timestamp: new Date().toISOString(),
            recommendations: recommendations.map(r => ({
                dishId: r.id,
                score: r.recommendationScore,
                reason: r.recommendationReason
            }))
        };
        
        history.unshift(record);
        if (history.length > 50) history.pop(); // 保留最近50次推荐
        
        this.recommendationHistory[userId] = history;
        localStorage.setItem('recommendationHistory', JSON.stringify(this.recommendationHistory));
    }

    // 加载用户偏好
    loadUserPreferences() {
        return JSON.parse(localStorage.getItem('userPreferences') || '{}');
    }

    // 加载推荐历史
    loadRecommendationHistory() {
        return JSON.parse(localStorage.getItem('recommendationHistory') || '{}');
    }

    // 更新用户偏好
    updateUserPreferences(userId, preferences) {
        this.userPreferences[userId] = preferences;
        localStorage.setItem('userPreferences', JSON.stringify(this.userPreferences));
    }

    // 获取推荐历史
    getRecommendationHistory(userId) {
        return this.recommendationHistory[userId] || [];
    }

    // 分析推荐效果
    analyzeRecommendationEffectiveness(userId) {
        const history = this.getRecommendationHistory(userId);
        if (history.length === 0) return null;

        const totalRecommendations = history.reduce((sum, record) => sum + record.recommendations.length, 0);
        const avgScore = history.reduce((sum, record) => {
            return sum + record.recommendations.reduce((s, r) => s + r.score, 0) / record.recommendations.length;
        }, 0) / history.length;

        return {
            totalRecommendations: totalRecommendations,
            averageScore: Math.round(avgScore),
            recommendationFrequency: history.length,
            lastRecommendation: history[0]?.timestamp
        };
    }

    // 用户行为学习
    learnFromUserBehavior(userId, action, data) {
        const userBehavior = JSON.parse(localStorage.getItem('userBehavior') || '{}');
        if (!userBehavior[userId]) {
            userBehavior[userId] = {
                clicks: [],
                orders: [],
                preferences: {},
                learningData: {}
            };
        }

        const behavior = userBehavior[userId];
        
        switch (action) {
            case 'click':
                behavior.clicks.push({
                    dishId: data.dishId,
                    timestamp: new Date().toISOString(),
                    context: data.context
                });
                break;
                
            case 'order':
                behavior.orders.push({
                    dishes: data.dishes,
                    timestamp: new Date().toISOString(),
                    context: data.context
                });
                break;
                
            case 'preference':
                behavior.preferences = { ...behavior.preferences, ...data };
                break;
        }

        // 更新学习数据
        this.updateLearningData(userId, behavior);
        
        // 保存行为数据
        localStorage.setItem('userBehavior', JSON.stringify(userBehavior));
    }

    // 更新学习数据
    updateLearningData(userId, behavior) {
        const learningData = {
            favoriteCategories: {},
            favoriteMerchants: {},
            favoriteDishes: {},
            timePatterns: {},
            pricePreferences: { min: 0, max: 0 },
            seasonalPreferences: {},
            weatherPreferences: {}
        };

        // 分析点击行为
        behavior.clicks.forEach(click => {
            const dish = this.getDishById(click.dishId);
            if (dish) {
                learningData.favoriteCategories[dish.category] = 
                    (learningData.favoriteCategories[dish.category] || 0) + 1;
                learningData.favoriteDishes[dish.id] = 
                    (learningData.favoriteDishes[dish.id] || 0) + 1;
            }
        });

        // 分析订单行为
        behavior.orders.forEach(order => {
            order.dishes.forEach(dish => {
                learningData.favoriteCategories[dish.category] = 
                    (learningData.favoriteCategories[dish.category] || 0) + 2; // 订单权重更高
                learningData.favoriteDishes[dish.id] = 
                    (learningData.favoriteDishes[dish.id] || 0) + 2;
            });
        });

        // 分析时间模式
        behavior.clicks.forEach(click => {
            const hour = new Date(click.timestamp).getHours();
            const timeSlot = this.getTimeOfDay(hour);
            learningData.timePatterns[timeSlot] = (learningData.timePatterns[timeSlot] || 0) + 1;
        });

        // 分析价格偏好
        const allPrices = [];
        behavior.orders.forEach(order => {
            order.dishes.forEach(dish => {
                allPrices.push(dish.price);
            });
        });
        
        if (allPrices.length > 0) {
            learningData.pricePreferences.min = Math.min(...allPrices);
            learningData.pricePreferences.max = Math.max(...allPrices);
        }

        behavior.learningData = learningData;
    }

    // 获取菜品信息
    getDishById(dishId) {
        const dishes = JSON.parse(localStorage.getItem('dishes') || '[]');
        return dishes.find(dish => dish.id === dishId);
    }

    // 获取用户行为数据
    getUserBehavior(userId) {
        const userBehavior = JSON.parse(localStorage.getItem('userBehavior') || '{}');
        return userBehavior[userId] || null;
    }

    // 生成个性化推荐理由
    generatePersonalizedReason(dish, userBehavior) {
        const reasons = [];
        const learningData = userBehavior?.learningData || {};

        // 基于历史偏好
        if (learningData.favoriteCategories[dish.category]) {
            reasons.push(`您喜欢${dish.category}类菜品`);
        }

        if (learningData.favoriteDishes[dish.id]) {
            reasons.push('您之前点过这道菜');
        }

        // 基于时间模式
        const currentHour = new Date().getHours();
        const currentTimeSlot = this.getTimeOfDay(currentHour);
        if (learningData.timePatterns[currentTimeSlot]) {
            reasons.push(`您经常在${currentTimeSlot === 'morning' ? '上午' : 
                currentTimeSlot === 'lunch' ? '午餐' : 
                currentTimeSlot === 'afternoon' ? '下午' : 
                currentTimeSlot === 'dinner' ? '晚餐' : '夜间'}点餐`);
        }

        // 基于价格偏好
        if (learningData.pricePreferences.min > 0 && 
            dish.price >= learningData.pricePreferences.min && 
            dish.price <= learningData.pricePreferences.max) {
            reasons.push('符合您的价格偏好');
        }

        return reasons.length > 0 ? reasons.join('，') : '为您精心推荐';
    }

    // 智能推荐优化
    optimizeRecommendations(userId, recommendations) {
        const userBehavior = this.getUserBehavior(userId);
        if (!userBehavior) return recommendations;

        // 基于用户行为调整推荐分数
        return recommendations.map(dish => {
            let adjustedScore = dish.recommendationScore;
            const learningData = userBehavior.learningData;

            // 类别偏好加成
            if (learningData.favoriteCategories[dish.category]) {
                adjustedScore += learningData.favoriteCategories[dish.category] * 2;
            }

            // 菜品偏好加成
            if (learningData.favoriteDishes[dish.id]) {
                adjustedScore += learningData.favoriteDishes[dish.id] * 5;
            }

            // 时间模式加成
            const currentHour = new Date().getHours();
            const currentTimeSlot = this.getTimeOfDay(currentHour);
            if (learningData.timePatterns[currentTimeSlot]) {
                adjustedScore += 10;
            }

            return {
                ...dish,
                recommendationScore: Math.max(0, adjustedScore),
                personalizedReason: this.generatePersonalizedReason(dish, userBehavior)
            };
        }).sort((a, b) => b.recommendationScore - a.recommendationScore);
    }
}

// 创建全局推荐引擎实例
window.aiRecommendationEngine = new AIRecommendationEngine();
